# coding=utf-8
'''
Created on 2015年5月28日
'''
import datetime
import json
from bson.objectid import ObjectId
import sys
import traceback
import time
import torndb
from protobuf_base.protobuf import UFOFileDict
# from google.protobuf.message import Message
import socket
import struct



class ComplexEncoder(json.JSONEncoder):
    '''
    encoder for json dumps
    '''
    
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, ObjectId):
            return obj.__str__()
        elif isinstance(obj, UFOFileDict):
            return obj.to_dict()
        else:
            return json.JSONEncoder.default(self, obj)
        
def raise_exception(e):
    '''
    '''
    raise e

def trace_error():
    '''
    trace exception info, output in sys.stdout
    '''
    
    etype, evalue, tracebackObj = sys.exc_info()[:3]
    print("Type: " , etype)
    print("Value: " , evalue)
    traceback.print_tb(tracebackObj)
    
def currentframe():
    '''
    Return the frame object for the caller's stack frame.
    '''
    
    try:
        raise Exception
    except:
        return sys.exc_info()[2].tb_frame.f_back

if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3)

    
def request_to_dict(request):
    '''
    将x-www-form-urlencoded形式的参数转化为dict
    '''
    
    arguments = {}
    map(lambda name: arguments.setdefault(name, request.arguments[name][0] if len(request.arguments[name]) == 1 else request.arguments[name]), request.arguments)
    
    return arguments

def is_web_request(user_agent):
    '''
    通过user_agent判断是否是web请求
    '''
    
    platforms = ['iPod', 'iPhone', 'Android']

    for item in platforms:
        if item in user_agent:
            return False
    
    return True

epoch = datetime.datetime.utcfromtimestamp(0)
##
# @brief 毫秒时间戳
#
def datetime_to_epoch(dt):
    '''
    Convert datetime object to epoch with millisecond accuracy
    '''
    delta = dt - epoch
    since_epoch = delta.total_seconds()
    return since_epoch

class TornDBConnector(object):
    '''
    简单的torndb操作类, 用于单独建立和销毁数据库连接
    '''
    
    def __init__(self, **settings):
        self.conn = torndb.Connection(**settings)
        
    def __enter__(self):
        '''
        '''
        return self.conn
        
    def __exit__(self, exc_type, exc_value, traceback):
        if self.conn:
            self.conn.close()
        
    def __del__(self):
        if self.conn:
            self.conn.close()

class Dict(dict):

    def __setattr__(self, key, value):
        self[key] = value

    def __getattr__(self, name):
        try:
            return self[name]
        except:
            raise

def sides_timestamp_of_the_month():
    # 返回当月月初到月末的时间戳范围
    today = datetime.datetime.today()
    start = str(datetime.date(today.year, today.month, 1))
    if today.month+1 > 12:
        end = str(datetime.date(today.year+1, 1, 1))
    else:
        end = str(datetime.date(today.year, today.month+1, 1))
    f = lambda t: int(time.mktime(time.strptime(t, '%Y-%m-%d')))
    return f(start), f(end)


def get_local_hostname():
    """
    本机主机名
    """
    return socket.getfqdn(socket.gethostname())


def deal_id_list_beta(id_list):
    """
    """
    if isinstance(id_list[0], int):
        return str(tuple([int(i) for i in id_list])).replace(',)', ')')
    else:
        return str(tuple(id_list)).replace(',)', ')')


def get_dawn_time():
    """
    获取凌晨时的时间戳
    """
    return int(time.mktime(datetime.date.today().timetuple()))


def time_stamp_to_utc_time(time_stamp):
    """
    时间戳转时间
    """
    utc_time = datetime.datetime.utcfromtimestamp(time_stamp)
    return str(utc_time)


def datetime_to_timestamp(datetime):
    """
    datetime转时间戳
    """
    timeArray = time.strptime(datetime, "%Y-%m-%d %H:%M:%S")
    timeStamp = int(time.mktime(timeArray))
    return timeStamp